package mr.go.yaxc.tests;

import mr.go.yaxc.tests.test3.RootLoggerAction;
import static org.junit.Assert.assertEquals;

import java.net.URL;

import mr.go.yaxc.ActionInfo;
import mr.go.yaxc.ActionMatch;
import mr.go.yaxc.Actions;
import mr.go.yaxc.XmlConfigurator;
import mr.go.yaxc.actions.New;
import mr.go.yaxc.actions.Ref;
import mr.go.yaxc.actions.SetObjectProperty;
import mr.go.yaxc.actions.SetProperty;
import mr.go.yaxc.tests.test3.Logger;
import mr.go.yaxc.tests.test3.LoggerFactory;

import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class Test3 {

    @BeforeClass
    public static void setUpBeforeClass()
            throws Exception {
        xmlUrl = Test3.class.getClassLoader().getResource("test3.xml");
        if (xmlUrl == null) {
            throw new IllegalStateException("No xml file");
        }
    }

    @AfterClass
    public static void tearDownAfterClass()
            throws Exception {
        Actions.resetConfiguration();
    }
    private XmlConfigurator configurator;

    @Before
    public void setUp()
            throws Exception {
        Actions.registerAction(
                SetObjectProperty.class,
                "configuration/appender",
                ActionMatch.CHILD_OF,
                Actions.PRIORITY_MAX);
        Actions.registerAction(
                RootLoggerAction.class,
                "configuration/root",
                ActionMatch.EQUALS,
                Actions.PRIORITY_MAX);
        final ActionInfo setPropertyActionInfo = Actions.getActionInfo(
                SetProperty.class);
        setPropertyActionInfo.setMatchType(ActionMatch.LEVEL);
        setPropertyActionInfo.setLevel(3);
        // Actions.setDefaultAction(setPropertyActionInfo);
        final ActionInfo newActionInfo = Actions.getActionInfo(New.class);
        newActionInfo.setPattern("/appender");
        newActionInfo.setAttributesMap("id",
                                       "name");
        final ActionInfo refActionInfo = Actions.getActionInfo(Ref.class);
        refActionInfo.setPattern("/root/appender-ref");
        refActionInfo.setAttributesMap("id",
                                       "ref");
        configurator = new XmlConfigurator();
        configurator.parse(xmlUrl);
    }

    @Test
    public void testRootLoggerConfig()
            throws Exception {
        final Logger rootLogger = LoggerFactory.getRootLogger();
        assertEquals("debug",
                     rootLogger.getLevel());
        assertEquals(
                "%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n",
                rootLogger.getAppender().getLayout().getPattern());
    }
    private static URL xmlUrl;
}
